<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>45、getSnapshotBeforeUpdate</title>
</head>
<body>
  <div id="test"></div>

  <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://cdn.staticfile.org/prop-types/15.6.1/prop-types.js"></script>

  <script type="text/babel">
    class Count extends React.Component{
      // 构造器
      constructor(props) {
        console.log('constructor')     
        super(props)

        this.state = {
          count: 0
        }
      }

      // 
      static getDerivedStateFromProps(props, state) {
        console.log('getDerivedStateFromProps', props, state)
        return null
      }

      // 在最近依次渲染输出（提交到DOM节点）之前调用
      // 在更新之前获取快照
      getSnapshotBeforeUpdate() {
        console.log('getSnapshotBeforeUpdate')
        return '111'
      }

      add = () => {
        // 获取原状态
        const {count} = this.state
        // 更新状态
        this.setState({count: count+1})
      }

      // 卸载组件按钮的回调
      death = () => {
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      // 强制更新按钮的回调
      force = () => {
        this.forceUpdate()
      }


      // 挂载时，组件挂载完毕的钩子，在render之后执行
      componentDidMount() {
        console.log('count-componentDidMount')
      }

      // 组件将要卸载的钩子
      componentWillUnmount() {
        console.log('count-componentWillUnmount')
      }

      // 控制组件更新的“阀门”
      shouldComponentUpdate() {
        console.log('count-shouldComponentUpdate')
        return true      // false之后，下面的钩子都不会执行
      }

      render() {
        console.log('count-render')
        const {count} = this.state
        return(
          <div>
            <h2>当前求和为{count}</h2>
            <button onClick={this.add}>点我+1</button>
            <button onClick={this.death}>点我卸载组件</button>
            <button onClick={this.force}>不更改任何状态中的数据、强制更新一下</button>
          </div>
        )
      }

      // 组件更新完毕的钩子
      componentDidUpdate(props, state) {
        console.log('count-componentDidUpdate', props, state)
      }
    }

    // react18不再使用ReactDOM.render渲染组件，而是使用react.createElement
    ReactDOM.render(<Count count={199}/>, document.getElementById('test'))
  </script>
</body>
</html>